package com.pitop.core;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by zhuzhengping on 2017/3/19.
 * aop切面，对每一个在controller请求之前做记录
 */
@Aspect
@Component
@Slf4j
public class HttpAspect {


    @Pointcut("execution(public * com.pitop.*.ctrl.*Ctrl.*(..))")//切面所切的位置
    public void log() {
    }

    @Before("log()")//请求之前
    public void before(JoinPoint joinPoint) {
        log.info(" >> request 前置拦截器");

        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        //url
        log.info(" >> 请求地址  url={}", request.getRequestURL());
        //method
        log.info(" >> HTTP方法 method={}", request.getMethod());
        //ip
        log.info(" >> 请求地址 id={}", request.getRemoteAddr());
        //class_method
        log.info(" >> 控制器方法 class_method={}", joinPoint.getSignature().getDeclaringTypeName() + "," + joinPoint.getSignature().getName());
        //args[]
        log.info(" >> 请求参数 args={}", joinPoint.getArgs());
    }

    @After("log()")//请求之后
    public void after() {
        log.info(" << request 后置拦截器");
    }

    @AfterReturning(pointcut = "log()", returning = "object")//打印输出结果
    public void doAfterReturing(Object object) {
        log.info(" << 控制器返回结果 response={}", object);
    }
}
